package com.lagou.edu.connector.protocol;

import com.lagou.edu.ProtocolEnum;
import com.lagou.edu.connector.Endpoint;
import com.lagou.edu.container.Engine;
import com.minicat.servlet.Request;
import com.minicat.servlet.Response;
import com.minicat.servlet.Servlet;

import java.io.IOException;
import java.net.Socket;

/**
 * 请求处理器
 *
 * @author liangzj
 * @date 2021/4/10 1:16
 */
public class Processor implements Runnable {

    private Endpoint endpoint;
    private Engine engine;

    public Processor(Endpoint endpoint, Engine engine) {
        this.endpoint = endpoint;
        this.engine = engine;
    }


    @Override
    public void run() {
        try {
            //根据协议处理请求
            if (ProtocolEnum.HTTP11.getProtocol().equalsIgnoreCase(endpoint.getProtocol())) {
                handleHttpRequest();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 第三版，处理动态资源
     *
     * @throws IOException
     */
    public void handleHttpRequest() throws IOException {

        try (Socket accept = endpoint.getAcceptor()) {
            Request request = new Request(accept.getInputStream());
            Response response = new Response(accept.getOutputStream());

            Mapper mapper = new Mapper(engine);
            Servlet servlet = mapper.mappedServlet(request.getHost(), request.getUrl());

            // 如果没有匹配到servlet，认为是静态文件
            if (servlet == null) {
                response.outputHtml(request.getUrl());
                return;
            }
            // 执行servlet
            servlet.service(request, response);

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 第二版，封装request和response对象，返回html
     *
     * @throws IOException
     */
    public void handleRequestV2(Request request, Response response) throws IOException {
        // output result
        response.outputHtml(request.getUrl());
    }

    /**
     * 第一版，返回固定字符串到浏览器
     *
     * @throws IOException
     */
    private void handleRequestV1() throws IOException {
//        Socket accept = connector.getAcceptor();
//        OutputStream outputStream = accept.getOutputStream();
//
//        String data = "Hello Minicat!";
//        String responseText = HttpProtocolMocker.mockHttpHeader200(data.getBytes(StandardCharsets.UTF_8).length) + data;
//
//        outputStream.write(responseText.getBytes(StandardCharsets.UTF_8));
//        accept.close();
    }
}
